package command;/**
 * @author XuXiaoK
 * @create 2020-01-21 13:19
 */

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 *@Author XiaoKe
 *@Date 2020/1/21 13:19
 *@Description TODO
 */
public class HelloCommand extends HystrixCommand<String> {

    private String url;
    CloseableHttpClient httpClient;

    @Override
    protected String getFallback() {
        System.out.println("执行HelloCommand回退方法");
        return "error";
    }

    public HelloCommand(String url) {
        // 调用父类的构造器，设置命令组的key
        // 默认用来作为线程池的key
        super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
        // 创建HttpClient客户端
        CloseableHttpClient httpClient = HttpClients.createDefault();
        this.url = url;
    }


    @Override
    protected String run() throws Exception {
        try {
            HttpGet httpGet = new HttpGet(url);
            HttpResponse response = httpClient.execute(httpGet);
            // 解析并返回命令执行结果
            return EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }
}
